<template>
  <div class="app-container">
    <wise-crud ref="wise-crud" :urls="urls" :fields="fields" :handle="handle">
      <template slot="outHandle">
        <el-col :span="3">
          <el-button v-permission="['superSysOpsAdmin', 'entAdmin','proAdmin','formalEmployee']" type="primary"
            @click="handleAdd()">
            <i class="el-icon-plus" />
            发起
          </el-button>
        </el-col>
      </template>
      <template v-slot:handle="slotProps" label-width="500px">
        <!-- 1 通过 2 驳回   11 待公司审批 12 待集团审批 -->
        <el-button v-if="slotProps.row.initiateStatus === 1 && !slotProps.row.projectId" type="success" size="small"
          round @click.native.prevent="createProjectHandle(slotProps.row)">
          创建
        </el-button>
        <el-button v-if="slotProps.row.initiateStatus === 2" type="primary" size="small" round
          @click.native.prevent="editHandle(slotProps.row)">
          编辑
        </el-button>
        <el-button type="info" size="small" round @click.native.prevent="viewHandle(slotProps.row)">查看</el-button>
        <el-button v-if="slotProps.row.initiateStatus != 1" v-permission="['superSysOpsAdmin', 'entAdmin']"
          type="danger" size="small" round @click.native.prevent="removeHandle(slotProps.row)">
          删除
        </el-button>
        <!-- <el-button
          v-permission="['superSysOpsAdmin', 'entAdmin']"
          type="warning"
          size="small"
          round
          @click.native.prevent="setTheme(slotProps.row)"
        >
          设置主题
        </el-button> -->
      </template>
    </wise-crud>
    <!-- 添加/编辑 -->
    <el-dialog ref="drawer" :title="title" :visible.sync="drawer" destroy-on-close>
      <div v-if="drawer" class="draw-body">
        <div class="wise-form">
          <el-form ref="ruleForm" :model="object" :rules="rules" :validate-on-rule-change="false" label-width="130px"
            label-suffix=":">
            <el-form-item v-if="object.rejectReason" label="驳回原因" prop="rejectReason">
              {{ object.rejectReason }}
            </el-form-item>
            <el-form-item label="问题选择" prop="problemTypeName">
              <el-radio-group v-model="object.problemTypeName">
                <el-radio v-for="(problem, index) in problemData" :key="index" :label="problem.name" />
              </el-radio-group>
            </el-form-item>
            <el-form-item label="项目计划" prop="ppId">
              <el-select v-model="object.ppId" filterable clearable placeholder="请选择项目计划">
                <el-option v-for="item in planListData" :key="item.id" :label="item.item_name" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="object.name" placeholder="请输入项目名称" clearable autofocus />
            </el-form-item>
            <el-form-item label="简单陈述" prop="depict">
              <el-input v-model="object.depict" placeholder="请输入简单陈述" :maxlength="100" show-word-limit clearable
                autofocus type="textarea" />
            </el-form-item>
            <el-form-item label="图片" prop="imageUrl">
              <wise-file v-model="object.imageUrl" :limit="6" upload-type="image" />
            </el-form-item>
            <el-form-item label="选择审批人" prop="approvalUserId">
              <el-select v-model="object.approvalUserId" placeholder="选择审批人" @change="onChangeApprovalId">
                <el-option v-for="(approval, index) in approvalData" :key="index" :label="approval.username"
                  :value="approval.userId" :disabled="approval.disabled" />
              </el-select>
            </el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')" :disabled="isDisabled">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <!-- 查看项目 -->
    <el-dialog ref="viewDrawer" title="查看项目" :visible.sync="viewDrawer" destroy-on-close>
      <div v-if="viewDrawer" class="draw-body">
        <div class="wise-form">
          <el-form :validate-on-rule-change="false" label-width="130px" label-suffix=":">
            <el-form-item label="问题" prop="problemTypeName">
              {{ object.problemTypeName }}
            </el-form-item>
            <el-form-item label="项目名称" prop="name">
              {{ object.name }}
            </el-form-item>
            <el-form-item label="陈述" prop="depict">
              {{ object.depict }}
            </el-form-item>
            <el-form-item v-if="object.imageUrl" label="图片" prop="imageUrl">
              <el-image v-for="(img, i) in object.imageUrl.split(';')" :key="i" class="image" fit="cover" alt="点击查看大图"
                :src="img | imgPath" :preview-src-list="getSrcList(object.imageUrl)" />
            </el-form-item>
            <el-form-item label="发起状态审批" prop="initiateStatus">
              {{ initiateStatusHandle(object.initiateStatus) }}
            </el-form-item>
            <el-form-item v-if="object.rejectReason" label="驳回原因" prop="rejectReason">
              {{ object.rejectReason }}
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-dialog>
    <!-- 主题弹层 -->
    <el-dialog title="设置主题" :visible.sync="themeDrawer" width="30%">
      <el-form ref="form" :model="themeObj" label-width="80px">
        <el-form-item label="设置主题">
          <el-select v-model="themeObj.code" clearable placeholder="请选择主题">
            <el-option label="绿松石蓝(默认)" value="default" />
            <el-option label="粉绿主题" value="theme2" />
            <el-option label="天蓝主题" value="theme3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setThemeHandle">确定</el-button>
          <el-button @click="themeDrawer = false">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 创建项目 -->
    <CreateProjectForm ref="createProjectForm" />
  </div>
</template>

<script>
  import WiseCrud from '@/components/Crud/wiseCrud'
  import WiseFile from '@/components/Crud/components/wiseFile'
  import {
    postHandle
  } from '@/api'
  import {
    setSpaceId
  } from '../../../../utils/auth'
  import {
    imgPath
  } from '@/filters'
  import CreateProjectForm from './CreateProjectForm.vue'

  export default {
    name: 'ProviderManage',
    components: {
      WiseCrud,
      WiseFile,
      CreateProjectForm
    },
    data() {
      return {
        urls: {
          list: '/api/v1/welder-sbtx-second/initiate-project-comb/list',
          add: '/api/v1/welder-sbtx-second/initiate-project-comb/create',
          show: '/api/v1/welder-sbtx-second/initiate-project-comb/show/',
          update: '/api/v1/welder-sbtx-second/initiate-project-comb/update/',
          delete: '/api/v1/welder-sbtx-second/initiate-project-comb/remove/'
        },
        fields: [{
            label: '序号',
            type: 'index',
            use: ['table']
          },
          {
            label: '项目名称',
            prop: 'name',
            type: 'text',
            use: ['table', 'view']
          },
          {
            label: '问题',
            prop: 'problemTypeName',
            type: 'text',
            use: ['table', 'view']
          },
          {
            label: '陈述',
            prop: 'depict',
            type: 'text',
            use: ['table', 'view']
          },
          {
            label: '发起审批状态',
            prop: 'initiateStatus',
            type: 'render',
            use: ['table', 'view'],
            tableRender: (h, row, index) => {
              return h('div', this.initiateStatusHandle(row.initiateStatus))
            },
            viewRender: (h, item, object) => {
              return h('div', this.initiateStatusHandle(object.initiateStatus))
            }
          },

          {
            label: '操作',
            type: 'handle',
            use: ['table'],
            handle: [],
            tableWidth: 240
          }
        ],
        planListData: [],
        handle: [],
        drawer: false,
        viewDrawer: false,
        themeDrawer: false,
        isDisabled: false,
        title: '发起项目',
        object: {
          problemTypeName: null,
          depict: null,
          approvalUserId: null,
          name: null,
          imageUrl: ''
        },
        nullUserId: null,
        isSubminBtn: false,
        rules: {
          problemTypeName: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          ppId: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          depict: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          approvalUserId: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }],
          name: [{
            required: true,
            message: '必填项不能为空',
            trigger: 'blur'
          }]
        },
        themeObj: {
          id: null,
          code: 'default'
        },
        problemData: [],
        approvalData: [],
        maxPageSize: {
          ps: 9999,
          p: 1
        }
      }
    },
    computed: {
      entSpaceId() {
        return this.$store.getters.entSpaceId
      }
      // filters() {
      //   if (this.$store.state.user.project) {
      //     return [
      //       {
      //         field: 'id',
      //         operator: 'EQUALS',
      //         value: this.$store.state.user.project.id
      //       }
      //     ]
      //   } else {
      //     return []
      //   }
      // }
    },

    created() {
      this.getApprovalData()
      this.getProblemData()
      // this.value = '6'
      // for (let i = 0; i < this.options.length; i++) {
      
      //   if (this.options[i].value != this.value) {
       
      //     this.options.push({
      //       value: this.value,
      //       label: '暂无'
      //     })
      //   } else {

      //   }
      // }
    },    mounted() {
        window.location.reload(true);
    },

    methods: {
      // 根据企业entSpaceId获取企业全部的管理员
      getApprovalData() {
        postHandle(`/api/v1/welder-uac-second/space-user-member-role-comb/get-ent-admin/${this.entSpaceId}`, {
          d: {
            page: this.maxPageSize
          }
        }).then(res => {
          this.approvalData = res.result
        })
         

        const req = {
            d: {
              filters: [{
                field: 'spaceId',
                operator: 'EQUALS',
                value: this.$store.getters.entSpaceId
              },
              {
                field: 'sp',
                operator: 'EQUALS',
                value: 1
              }
            ],
              page: {
                p: 1,
                ps: 9999
              }
            }
          }
        postHandle('/api/v1/welder-sbtx-second/project-plan/getPPlist', req).then(response => {
            const data = response.result
            this.planListData = data
        })
      },
      // 问题选择
      getProblemData() {
        let params = {
          d: {
            filters: [{
              field: 'pdCode',
              operator: 'EQUALS',
              value: 'problem'
            }],
            page: this.maxPageSize,
            sorts: [{
              field: 'ct',
              isDesc: false
            }]
          }
        }
        postHandle('/api/v1/welder-sbtx-second/dictionary', params).then(res => {
          this.problemData = res.result
        })
      },
      // 发起状态审批
      initiateStatusHandle(state) {
        let value
        switch (state) {
          case 1:
            value = '通过'
            break
          case 2:
            value = '驳回'
            break
          case 11:
            value = '待公司审批'
            break
          case 12:
            value = '待集团审批'
            break
          default:
            value = '暂无数据'
        }
        return value
      },
      // 问题
      problemTypeHandle(code) {
        if (code) {
          let obj = this.problemData.find(item => item.code === code)
          if (obj) {
            return obj.name
          } else {
            return '暂无数据'
          }
        }
      },
      handleAdd() {
        this.title = '发起项目'
        this.object = {
          name: null
        }
        this.drawer = true
      },
      editHandle(row) {


        this.title = '编辑项目'
        this.object = {
          imageUrl: ''
        }
        this.fileList = []
        this.getObjectById(row.id)
        this.drawer = true
      },
      viewHandle(row) {
        this.getObjectById(row.id)
        this.viewDrawer = true
      },
      removeHandle(row) {
        this.$confirm('您确定要删除该项目, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(() => {
            this.removeById(row.id)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      },
      onChangeApprovalId(val) {
        if (val !== this.nullUserId) {
          this.isSubminBtn = false
        }
      },
      // 详情
      getObjectById(id) {
        postHandle(this.urls.show + id, {}).then(response => {
          this.object = response.result
          let data = response.result
          this.nullUserId = data.approvalUserId
          if (this.approvalData.findIndex(item => item.userId == data.approvalUserId) === -1) {
            this.isSubminBtn = true
            this.approvalData.push({
              userId: data.approvalUserId,
              username: "用户不存在",
              disabled: true
            })
          }
        })
      },
      // 删除
      removeById(id) {
        postHandle(this.urls.delete + id, {})
          .then(response => {
            this.$message('删除成功')
            this.themeDrawer = false
            this.$refs['wise-crud'].handleSearch(1)
          })
          .catch(error => {
            this.loading = false
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(data[key]))
            }
          })
      },
      // 提交
      submitForm(formName) {
        if (this.isSubminBtn) {
          this.$message('用户不存在')
          return false
        }
        this.$refs[formName].validate(valid => {
          if (valid) {
            this.isDisabled = true
            let url
            let problemTypeObj
            let obj = JSON.parse(JSON.stringify(this.object))
            if (this.object.problemTypeName) {
              problemTypeObj = this.problemData.find(item => item.name === this.object.problemTypeName)
            }
            if (this.object.id) {
              url = this.urls.update + this.object.id
            } else {
              url = this.urls.add
            }
            if (problemTypeObj) {
              this.$set(obj, 'problemType', problemTypeObj.code)
            }
            postHandle(url, {
                obj
              })
              .then(response => {
                this.$message('操作成功')
                this.drawer = false
                this.isDisabled = false
                if (this.object.id) {
                  this.$refs['wise-crud'].handleSearch(0)
                } else {
                  this.$refs['wise-crud'].handleSearch(1)
                }
              })
              .catch(error => {
                const data = error.response.data
                for (const key in data) {
                  this.$message.error(this.$t(key + '.' + data[key]))
                }
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 重置
      resetForm(formName) {
        this.object = {
          problemTypeName: null,
          depict: null,
          approvalUserId: null,
          name: null,
          imageUrl: ''
        }

        // this.$refs[formName].resetFields()
      },
      // 项目管理
      screenMonitor(row) {
        // if(row.isneiwang==1){
        //   // let routeUrl = this.$router.resolve({
        //   //         path: row.cturl// 这里的路径就可以正常的写，不需要添加_blank: true
        //   // })
        //   // window.open(routeUrl.href, '_blank')
        //   window.location.href = row.cturl;
        // }else{
          setSpaceId(row.spaceId)
          window.location.href = '/project'
        //}
      },
      // 设置主题
      setTheme(row) {
        // this.themeObj.id = row.id
        // this.themeObj.projectId = row.projectId
        this.themeObj.id = row.projectId
        this.themeObj.code = row.code ? row.code : 'default'
        this.themeDrawer = true
      },
      // 设置主题
      setThemeHandle() {
        postHandle(`/api/v1/welder-sbtx-second/project-info-comb/update-project-code/${this.themeObj.id}`, {
            d: {},
            obj: this.themeObj
          })
          .then(response => {
            this.$message('操作成功')
            this.themeDrawer = false
            this.$refs['wise-crud'].handleSearch(1)
          })
          .catch(error => {
            const data = error.response.data
            for (const key in data) {
              this.$message.error(this.$t(key + '.' + data[key]))
            }
          })
      },
      getSrcList(str) {
        let arr = []
        if (str) {
          arr = str.split(';')
        }
        return arr.map(item => imgPath(item))
      },
      createProjectHandle({
        id,
        name
      }) {
        this.$refs['createProjectForm'].title = '创建项目'
        this.$refs['createProjectForm'].object.name = name
        this.$refs['createProjectForm'].initiateProjectId = id
        this.$refs['createProjectForm'].drawer = true
      }
    }
  }
</script>

<style lang="less" scoped>
  .image {
    width: 150px;
    height: 150px;
    margin-right: 10px;
  }
</style>